<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      :control="control"
      :controlPosition="[]"
      :positionName="''"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    >
 <template #add ><el-button @click="addHeader" v-permission="'ticket/create'" color="#50BC58"  icon="Plus" circle class="ml-4 button"></el-button></template>
    </TopSearch>
    <ProTable
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="rowControl"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @row-control-click="onRowControlClick"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
    >
      <template #default="{ row, propname }">
        <div v-if="propname === 'ticket_item'">
                        <ProTable
                            :data="row[propname]"
                            :column="{  num:'套票數量',price:'金額',deadline:'使用期限(天)'}"
                            :elProps="{border:true}"
                            :page="[]"
                            :rowControl="[]"
                            :disabled="[]"
                            :controlWidth="[]"
                            >
                        </ProTable>
        </div>
      </template>
              <template #search_operate>
            <el-table-column  fixed="right" min-width="150px" label="操作">
              <template #default="scope" >
                <div class="flex justify-around">
                <el-link v-permission="'ticket/update'"  @click="onRowControlClick(scope.row, 'rowedit')" type="primary" :underline="false" >查看</el-link >
                <el-link v-permission="'ticket/delete'"  @click="onRowControlClick(scope.row, 'rowdel')" type="primary" :underline="false" >刪除</el-link >
                </div>
              </template>
            </el-table-column>
        </template>
    </ProTable>
         <addEdit ref="AddEditref" :echo="echo" @addConfirm="addConfirm" :courseList="courseList"></addEdit>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { elProps,controlWidth } from "./index.js";
import { setFormConfig } from "./formConfig";
import addEdit from "./addEdit/index.vue";
import { tickets,delTickets,course} from "@/http/index.js";
import { loading, closeLoading,messageBox,message } from "@/common/function.js";

const echo = ref({});
// 添加編輯彈窗
const AddEditref = ref('');
// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  number:'編號',
  name:'套票名稱',
  // deadline: "過期天數",
  ticket_item: "套票規格",
};
// 表格顶部操作按钮
const control = ["search", "dels"];

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const searchHeader = (e, type) => {
  Object.assign(obj, e);
  tableList(obj);
};

const dialogValue = ref(false);

const addHeader = async() => {
     await courseData()
  AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = "add"
echo.value = {
    name: "",
    deadline: "",//期限
    course_id:'',         //課程id
    ticket_item:[],//套票規格
}
  dialogValue.value = true;

};
const courseList = ref([])
const courseData =async ()=>{
  let res = Object.assign(obj,{school_id:localStorage.getItem('school_id')})
    const data = await course(res)
    console.log(data);
    if (data.code == 200) {
        courseList.value = data.data.data
    }
}
// 表格行内操作按钮
const rowControl = ["rowedit", "rowdel"];

/**表格行内操作
 * @row {object} 行内数据
 * @type {string} 点击按钮类型
 */
const onRowControlClick = async (row,type) => {
  console.log(row);
  if (type == "rowedit") {
          courseData()
    const { id, name, deadline,course_id, ticket_item} = row;
    echo.value ={ id, name, deadline, ticket_item} 
    if (course_id) {
        echo.value.course_id = course_id.split(',').map(Number)
    }
    console.log(echo.value);
   AddEditref.value.buttonType = "edit"
    AddEditref.value.dialogValue = true;
  }
  if (type == 'rowdel') {
        messageBox().then(async () => {
        await delTableList(row.id) 
    })
  }
}
// 刪除套票
const delTableList = async (id)=>{
  const data = await delTickets(id)
  if (data.code == 200) {
    await tableList(obj)
    message('成功刪除套票')
  }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
  let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};

const delsHeader = () => {
    messageBox().then(async () => {
        await delTableList(ids.value) 
    })
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange = async ({ e, type }) => {
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e
  }
  await tableList()
};
const tableData = ref([])
const obj = reactive({
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
});
const tableList = async ()=>{
  loading()
  const data = await tickets(obj)
  if (data.code == 200) {
    tableData.value = data.data.data
    page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    console.log( tableData.value);
  }
  closeLoading()
}

const pageRefresh = async () => {
  await tableList();
};
const addConfirm = async()=>{
   await tableList();
}
onMounted(() => {
  tableList();
});

</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.box {
  padding: 16px 33px;
}
.button{
  color: #fff;
}

</style>